#include "Game.h"

	Game *Game::Create()
	{
		Game *game=new Game();
		
		if (game->Init())
		{
			return game;
		}
		delete game;
		return NULL;
	}

	Game::~Game()
	{
		delete m_window;
		delete m_artman;
		delete m_stateman;
	}

	void Game::Run()
	{
		  while (m_window->isOpen() && m_play)
		 {
			sf::Event event;
			while (m_window->pollEvent(event))
			{
				if (event.type == sf::Event::Closed)
				m_window->close();
				if (event.type == sf::Event::LostFocus)
				{
					m_focus=false;
				}
				if (event.type== sf::Event::GainedFocus)
				{
					m_focus=true;
				}
			}
			while (m_lastupdate.asMilliseconds()>m_clock.getElapsedTime().asMilliseconds()-33)
			{
				//wait
				sf::sleep(sf::milliseconds(16));
			}
			Update((m_clock.getElapsedTime().asMilliseconds()-m_lastupdate.asMilliseconds()));
			m_lastupdate=m_clock.getElapsedTime();
			

		}
	}

	Game::Game()
	{
		m_play=true;
		m_focus=true;
	}

	bool Game::Init()
	{
		m_window=new sf::RenderWindow(sf::VideoMode(1280, 768), "White Night");
	
		m_clock.restart();
		m_lastupdate=m_clock.getElapsedTime();
		m_stateman=new Stateman(4);		
		m_artman=new Artman();
		m_stateman->Addstate(GameplayState::Create(m_artman));
		m_stateman->EnterState(0);

		return true;
	}

	void Game::Update(float dt)
	{
			
			if (m_focus)
			{
				m_stateman->getCurrentState()->Update(dt);
			}
			m_window->clear();
			m_stateman->getCurrentState()->Draw(*m_window);
		
			m_window->display();
	}